﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Xml.XPath;
using Songhay.Data.Common;
using Songhay.Data.GenericWeb.Properties;
using Songhay.Xml;

namespace Songhay.Data.GenericWeb.Procedure
{
    /// <summary>
    /// Insert procedures for Web-schema data.
    /// </summary>
    internal static partial class Insert
    {
        internal static XPathDocument Segment(DbConnection commonConnection, IXPathNavigable navigableInput)
        {
            XPathNavigator node = XmlUtility.GetNavigableNode(navigableInput, "//FormData");

            Dictionary<string, object> paramSet = new Dictionary<string, object>();
            object p = null;

            p = XmlUtility.GetNodeValue(node, "./SegmentName", true, DBNull.Value);
            paramSet.Add("@SegmentName", p);

            p = XmlUtility.GetNodeValue(node, "./SortOrdinal", true, DBNull.Value);
            paramSet.Add("@SortOrdinal", p);

            p = XmlUtility.GetNodeValueAndParse<DateTime>(node, "./CreateDate", true, DateTime.Now);
            paramSet.Add("@CreateDate", p);

            p = XmlUtility.GetNodeValue(node, "./ParentSegmentId", true, DBNull.Value);
            paramSet.Add("@ParentSegmentId", p);

            p = XmlUtility.GetNodeValue(node, "./ClientId", true, DBNull.Value);
            paramSet.Add("@ClientId", p);

            p = XmlUtility.GetNodeValue(node, "./IsActive", true, DBNull.Value);
            paramSet.Add("@IsActive", p);

            using(DbCommand cmd = commonConnection.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = Resources.InsertSegment;

                DbParameter[] paramArray = CommonParameter.GetParameters(cmd, paramSet);
                cmd.Parameters.AddRange(paramArray);

                p = cmd.ExecuteScalar();

                return Get.SegmentForEdit(commonConnection, p.ToString());
            }
        }
    }
}
